<template>
  <div class="boss-management">
    <el-card class="box-card">
      <!-- 搜索区域 -->
      <el-form 
        :inline="true" 
        :model="searchForm" 
        class="search-form"
        size="mini"
      >
        <el-form-item label="老板ID">
          <el-input 
            v-model="searchForm.id" 
            placeholder="请输入ID" 
            clearable
            style="width: 120px"
          ></el-input>
        </el-form-item>

        <el-form-item label="老板昵称">
          <el-input 
            v-model="searchForm.nickname" 
            placeholder="请输入昵称" 
            clearable
            style="width: 160px"
          ></el-input>
        </el-form-item>

        <el-form-item label="余额范围">
          <el-input-number 
            v-model="searchForm.minMoney" 
            placeholder="最小" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
          <span class="range-separator">-</span>
          <el-input-number 
            v-model="searchForm.maxMoney" 
            placeholder="最大" 
            :min="0"
            style="width: 100px"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="性别">
          <el-select 
            v-model="searchForm.bossSex" 
            placeholder="请选择" 
            clearable
            style="width: 120px"
          >
            <el-option label="男" value="0"></el-option>
            <el-option label="女" value="1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="地址">
          <el-select 
            v-model="searchForm.addressName" 
            placeholder="请选择" 
            clearable
            style="width: 160px"
          >
            <el-option 
              v-for="item in addressList" 
              :key="item.id" 
              :label="item.addressName" 
              :value="item.addressName"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item class="search-btns">
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 列表表格 -->
      <el-table 
        :data="bossList" 
        style="width: 100%" 
        v-loading="loading"
        border
        stripe
        size="mini"
      >
        <el-table-column prop="id" label="老板ID" width="80" align="center"></el-table-column>
        <el-table-column prop="bossNickname" label="老板昵称" align="center"></el-table-column>
        <el-table-column prop="bossName" label="真实姓名" align="center"></el-table-column>
        <el-table-column prop="addressName" label="地址" align="center"></el-table-column>
        <el-table-column prop="bossMoney" label="账户余额" align="center">
          <template slot-scope="scope">{{ scope.row.bossMoney ? scope.row.bossMoney.toFixed(2) : '0.00' }}</template>
        </el-table-column>
        <el-table-column prop="bossSex" label="性别" align="center">
          <template slot-scope="scope">{{ scope.row.bossSex === 0 ? '男' : '女' }}</template>
        </el-table-column>
        <el-table-column prop="userStatus" label="状态" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.userStatus === 0 ? 'success' : 'danger'" 
              size="mini"
            >
              {{ scope.row.userStatus === 0 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" align="center"></el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template slot-scope="scope">
            <el-button 
              size="mini" 
              type="text" 
              @click="handleDetail(scope.row)"
              icon="el-icon-view"
            >
              查看详情
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleChangeStatus(scope.row)"
              :icon="scope.row.userStatus === 0 ? 'el-icon-lock' : 'el-icon-unlock'"
              :class="scope.row.userStatus === 0 ? 'lock-btn' : 'unlock-btn'"
            >
              {{ scope.row.userStatus === 0 ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="mini" 
              type="text" 
              @click="handleDelete(scope.row)"
              icon="el-icon-delete"
              class="delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
        size="mini"
      ></el-pagination>
    </el-card>

    <!-- 状态修改弹窗 -->
    <el-dialog 
      :title="dialogTitle" 
      :visible.sync="dialogVisible" 
      width="40%"
      center
      size="mini"
    >
      <el-form 
        :model="editForm" 
        label-width="120px" 
        ref="editFormRef"
        :rules="formRules"
        size="mini"
      >
        <el-form-item label="老板ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="userStatus">
       <el-select v-model="editForm.userStatus" placeholder="请选择">
  <el-option label="启用" value="启用"></el-option> <!-- 原 value="0" -->
  <el-option label="禁用" value="禁用"></el-option> <!-- 原 value="1" -->
</el-select>
        </el-form-item>
      </el-form>
      <span slot="footer">
        <el-button @click="dialogVisible = false" size="mini">取消</el-button>
        <el-button type="primary" @click="saveStatus" size="mini">确定</el-button>
      </span>
    </el-dialog>

    <!-- 老板详情弹窗 -->
    <el-dialog 
      title="老板详情" 
      :visible.sync="detailVisible" 
      width="60%"
      destroy-on-close
    >
      <el-row :gutter="20">
        <!-- 基本信息区域 -->
        <el-col :span="24">
          <h3>基本信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="老板姓名">{{ detailForm.bossName || '-' }}</el-descriptions-item>
            <el-descriptions-item label="老板昵称">{{ detailForm.bossNickname || '-' }}</el-descriptions-item>
            <el-descriptions-item label="头像">
              <img 
                v-if="detailForm.bossAvatar" 
                :src="detailForm.bossAvatar" 
                style="width:60px;height:60px;border-radius:50%"
              >
              <span v-else>无头像</span>
            </el-descriptions-item>
            <el-descriptions-item label="性别">
              {{ detailForm.bossSex === 0 ? '男' : detailForm.bossSex === 1 ? '女' : '-' }}
            </el-descriptions-item>
            <el-descriptions-item label="自我介绍">{{ detailForm.bossDesc || '-' }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ detailForm.bossEmail || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 游戏相关信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>游戏相关信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="游戏爱好">{{ detailForm.bossGameHobby || '-' }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag 
                :type="detailForm.userStatus === 0 ? 'success' : 'danger'"
              >
                {{ detailForm.userStatus === 0 ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 财务信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>财务信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="账户余额">{{ detailForm.bossMoney !== undefined ? detailForm.bossMoney.toFixed(2) + ' 元' : '0.00 元' }}</el-descriptions-item>
            <el-descriptions-item label="关联地址">{{ detailForm.addressName || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
        
        <!-- 其他信息 -->
        <el-col :span="24" style="margin-top:15px">
          <h3>其他信息</h3>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="创建时间">{{ detailForm.createTime || '-' }}</el-descriptions-item>
            <el-descriptions-item label="最后更新时间">{{ detailForm.updateTime || '-' }}</el-descriptions-item>
          </el-descriptions>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false" size="mini">关闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import adminApi from '@/http/adminApi.js';

export default {
  name: 'AdminBossManagement',
  data() {
    return {
      addressList: [],
      searchForm: {
        id: null,
        nickname: '',
        minMoney: null,
        maxMoney: null,
        bossSex: null,
        addressName: '',
        page: 1,
        pageSize: 10,
        tenantId: 1 // 假设租户ID固定为1
      },
      bossList: [],
      loading: false,
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogVisible: false,
      detailVisible: false,
      dialogTitle: '修改状态',
      editForm: {
        id: null,
        userStatus: null
      },
      detailForm: {},
      defaultAvatar: 'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png',
      formRules: {
        userStatus: [{ required: true, message: '请选择状态', trigger: 'change' }]
      }
    };
  },
  mounted() {
    this.initData();
  },
  methods: {
    async initData() {
      await this.fetchAddressList();
      await this.fetchBossList();
    },

    async fetchAddressList() {
      this.loading = true;
      try {
        const res = await adminApi.getAddressList();
        this.addressList = res.data || [];
      } catch (error) {
        this.$message.error('获取地址失败');
      } finally {
        this.loading = false;
      }
    },

    async fetchBossList() {
      this.loading = true;
      try {
        const res = await adminApi.getBossList(this.searchForm);
        if (res.code === 200) {
          this.bossList = res.data.list || [];
          this.total = res.data.total || 0;
        }
      } catch (error) {
        this.$message.error('获取老板列表失败');
      } finally {
        this.loading = false;
      }
    },

    handleSearch() {
      this.currentPage = 1;
      this.searchForm.page = 1;
      this.fetchBossList();
    },

    resetSearch() {
      this.searchForm = {
        ...this.searchForm,
        id: null,
        nickname: '',
        minMoney: null,
        maxMoney: null,
        bossSex: null,
        addressName: ''
      };
      this.handleSearch();
    },

    handleSizeChange(val) {
      this.pageSize = val;
      this.searchForm.pageSize = val;
      this.fetchBossList();
    },

    handleCurrentChange(val) {
      this.currentPage = val;
      this.searchForm.page = val;
      this.fetchBossList();
    },

    // 状态切换方法
    async handleChangeStatus(row) {
      const newStatus = row.userStatus === 0 ? 1 : 0;
      const statusText = newStatus === 0 ? '启用' : '禁用';
      
      try {
        await this.$confirm(`确定要${statusText}该老板吗？`, '确认操作', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        this.loading = true;
        const res = await adminApi.updateBossStatus({
          id: row.id,
          userStatus: newStatus
        });
        
        if (res.code === 200) {
          this.$message.success(`${statusText}成功`);
          this.fetchBossList();
        } else {
          this.$message.error(res.message || `${statusText}失败`);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('操作异常');
        }
      } finally {
        this.loading = false;
      }
    },

    async handleEdit(row) {
      this.dialogTitle = '修改老板状态';
      this.editForm = {
        id: row.id,
        // 核心修改：数字映射为中文
        userStatus: row.userStatus === 0 ? '启用' : '禁用'
      };
      this.dialogVisible = true;
    },

    async saveStatus() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (valid) {
          // 转换中文为数字
          const submitData = {
            id: this.editForm.id,
            userStatus: this.editForm.userStatus === '启用' ? 0 : 1
          };
          try {
            await adminApi.updateBossStatus(submitData); // 传入转换后的数据
            this.$message.success('修改成功');
            this.dialogVisible = false;
            this.fetchBossList();
          } catch (error) {
            this.$message.error('修改失败');
          }
        }
      });
    },

    async handleDelete(row) {
      try {
        await this.$confirm('确定删除该老板吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        const res = await adminApi.deleteBoss({ id: row.id });
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.fetchBossList();
        } else {
          this.$message.error(res.message);
        }
      } catch (error) {
        if (error !== 'cancel') {
          this.$message.error('删除失败');
        }
      }
    },
    
    // 查看详情
    async handleDetail(row) {
      try {
        const res = await adminApi.getBossDetail({ id: row.id });
        if (res.code === 200) {
          this.detailForm = res.data;
          this.detailVisible = true;
        }
      } catch (error) {
        this.$message.error('获取详情失败');
      }
    }
  }
};
</script>

<style scoped>
.search-form {
  margin: 10px 0 20px;
  padding: 10px 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}
.range-separator {
  margin: 0 8px;
}
.search-btns {
  margin-left: 10px;
}
.pagination {
  margin-top: 20px;
  text-align: right;
}
.delete-btn {
  color: #f56c6c;
}

.avatar-container {
  text-align: center;
  padding: 20px 0;
}

.boss-avatar {
  margin: 0 auto 15px;
  width: 120px;
  height: 120px;
}

.boss-name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.boss-nickname {
  color: #606266;
  margin-bottom: 10px;
}

.desc-label {
  vertical-align: top;
  padding-top: 5px;
}

.self-desc {
  line-height: 1.6;
  white-space: pre-wrap;
  word-break: break-all;
}

.lock-btn {
  color: #e6a23c;
}
.unlock-btn {
  color: #67c23a;
}

/* 详情弹窗分模块标题样式：对齐陪玩弹窗 */
.el-dialog h3 {
  font-size: 16px;
  font-weight: 500;
  color: #1d2129;
  margin-bottom: 12px;
  padding-left: 8px;
  border-left: 3px solid #409eff;
}

/* 描述列表样式优化：对齐陪玩弹窗 */
.el-descriptions {
  margin-bottom: 0;
}
.el-descriptions__label {
  color: #4e5969;
  font-weight: 400;
}
.el-descriptions__content {
  color: #1d2129;
}

/* 弹窗底部按钮组：对齐陪玩弹窗样式 */
.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  padding: 12px 20px;
  background-color: #f8f9fa;
  border-top: 1px solid #ebeef5;
  border-radius: 0 0 8px 8px;
}
</style>